<template>
  <div class="login-container">
    <div class="login-box">
      <h1 class="login-title">欢迎回来</h1>
      <el-form
        ref="formRef"
        :model="loginForm"
        label-position="top"
        class="login-form"
        @submit.native.prevent="handleLogin"
      >
        <el-form-item
          prop="username"
          required
        >
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            clearable
            @keyup.enter="handleLogin"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          prop="password"
          required
        >
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            clearable
            show-password
            @keyup.enter="handleLogin"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          prop="captchaAnswer"
          required
        >
          <div class="captcha-wrapper">
            <el-input
              v-model="loginForm.captchaAnswer"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="Picture"
              clearable
              maxlength="4"
              style="flex:1;margin-right:10px"
              @keyup.enter="handleLogin"
            >
            </el-input>

            <img
              :src="captchaImage"
              class="captcha-image"
              @click="refreshCaptcha"
            />
          </div>
        </el-form-item>
        <div class="login-options">
          <el-checkbox
            v-model="loginForm.rememberPwd"
            @keyup.enter="handleLogin"
          >记住密码</el-checkbox>
          <el-link
            type="primary"
            :underline="false"
          >忘记密码?</el-link>
        </div>

        <el-button
          type="primary"
          class="login-btn"
          @click="handleLogin"
          size="large"
        >
          立即登录
        </el-button>
      </el-form>
      <div class="login-footer">
        <p style="display: inline; margin-right: 8px; font-size: 14px"> 没有账号？</p>
        <el-link
          type="primary"
          :underline="false"
          @click="$router.push('register')"
        >去注册</el-link>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { getCaptcha, login } from '@/api/user'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import Logger from '@/util/log'
import { loginResult } from '@/util/session'
import { isResultSuccess } from '@/util/http'

const formRef = ref()
// const表单数据
const loginForm = ref({
  username: '',
  password: '',
  captchaID: '',
  captchaAnswer: '',
  rememberPwd: false
})

const captchaImage = ref('')
const router = useRouter()
const refreshCaptcha = async () => {
  try {
    const res = await getCaptcha()
    loginForm.value.captchaID = res.data.captchaID
    captchaImage.value = res.data.captchaImage
    loginForm.value.captchaAnswer = '' // 重置验证码答案
  } catch (err) {
    ElMessage.error('验证码加载失败', err.message.data)
  }
}

const handleLogin = () => {
  formRef.value.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      try {
        const res = await login(loginForm.value)
        Logger.prettyInfo('login res', res)
        if (res && isResultSuccess(res)) {
          loginResult({
            token: res.data.token,
            account: res.data.account,
            nickname: res.data.nickname,
            email: res.data.email,
            rememberPwd: loginForm.value.rememberPwd,
          })
          ElMessage.success('登录成功')
          router.push('/')
          return true
        }
        // 理论上这里是不会走的
        // else {
        //   ElMessage.error('登录失败: ' + res.response.data.msg)
        //   refreshCaptcha()
        // }
        return false
      } catch (err) {
        ElMessage.error('请求登录失败： ' + err.response.data.msg)
        refreshCaptcha()
      }
    } else {
      Logger.prettyInfo('login form validate failed', fields)
      return false
    }
  })
}

onMounted(() => {
  refreshCaptcha()
})

</script>

<style scoped>
.login-container {
  height: 100vh;
  background: url('@/assets/login-bg.png') no-repeat center/cover;
  position: relative;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: absolute;
  right: 18%;
  top: 50%;
  transform: translateY(-50%);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #2d3a4b;
  font-weight: 600;
}

.login-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #5a5e66;
  }
}

.captcha-wrapper {
  display: flex;
  align-items: center;

  .captcha-image {
    width: 120px;
    height: 40px;
    border-radius: 4px;
    cursor: pointer;
    border: 1px solid #dcdfe6;
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

.login-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  color: #888;
  font-size: 14px;
}
</style>